import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTimeStamp } from '@/utils/auth'
import router from '@/router'

const tokenTimeout = 360000

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      if (isOut()) {
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('token过期'))
      }
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // console.log(response)
    const { success, message: mess, data } = response.data
    if (success) {
      return data
    } else {
      Message.error(mess)
      return Promise.reject(new Error(mess))
    }
  },
  error => {
    // console.log(error);
    if (error.response && error.response.data && error.response.data.code === 10002) {
      store.dispatch('user/logout')
      router.push('/login')
    }
    Message.error(error.mess)
    return Promise.reject(error)
  }
)
function isOut() {
  var timeStamp = getTimeStamp()
  var nowTime = Date.now()
  return (nowTime - timeStamp) / 1000 > tokenTimeout
}
export default service
